/**
 * @file popup.js
 * @author YnnSon
 * @description 弹出窗口的JavaScript逻辑，处理存储操作
 * @created 2025-08-07
 */
document.addEventListener('DOMContentLoaded', async () => {
  // DOM元素
  const currentUrlEl = document.getElementById('current-url');
  const jsonOutput = document.getElementById('json-output');
  const pasteInput = document.getElementById('paste-input');
  const readBtn = document.getElementById('read-btn');
  const copyBtn = document.getElementById('copy-btn');
  const writeBtn = document.getElementById('write-btn');
  const readClearBtn = document.getElementById('read-clear-btn');
  const writeClearBtn = document.getElementById('write-clear-btn');
  const copyToMemoryBtn = document.getElementById('copy-to-memory-btn');
  const pasteFromClipboardBtn = document.getElementById('paste-from-clipboard-btn');
  const pasteFromMemoryBtn = document.getElementById('paste-from-memory-btn');
  const loader = document.getElementById('loader');
  const notification = document.getElementById('notification');
  const tabs = document.querySelectorAll('.tab');
  const readStorageTitle = document.getElementById('read-storage-title');
  const writeStorageTitle = document.getElementById('write-storage-title');

  // 状态变量
  let currentTab = null;
  let currentStorageType = 'localStorage';
  loader.style.display = 'none';

  // 获取当前活动标签页
  try {
    [currentTab] = await chrome.tabs.query({ active: true, currentWindow: true });
    if (currentTab?.url) {
      const url = new URL(currentTab.url);
      currentUrlEl.textContent = `${url.hostname}${url.pathname}`;
    }
  } catch (error) {
    console.error('获取当前标签页失败:', error);
    currentUrlEl.textContent = '无法访问此页面';
  }

  // 存储类型标签切换
  tabs.forEach(tab => {
    tab.addEventListener('click', () => {
      tabs.forEach(t => t.classList.remove('active'));
      tab.classList.add('active');
      currentStorageType = tab.dataset.type;
      readStorageTitle.textContent = tab.textContent;
      writeStorageTitle.textContent = tab.textContent;
      jsonOutput.value = '';
      pasteInput.value = '';
    });
  });

  // 读取按钮事件
  readBtn.addEventListener('click', async () => {
    if (!isAllowOperate(currentTab)) return;
    if (!currentTab?.id) {
      showNotification('无法访问当前页面');
      return;
    }

    loader.style.display = 'flex';

    try {
      // 根据不同存储类型执行读取
      let data = {};

      if (currentStorageType === 'localStorage') {
        const result = await chrome.scripting.executeScript({
          target: { tabId: currentTab.id },
          func: () => {
            const data = {};
            for (let i = 0; i < localStorage.length; i++) {
              const key = localStorage.key(i);
              data[key] = localStorage.getItem(key);
            }
            return data;
          }
        });
        data = result[0].result;
      }
      else if (currentStorageType === 'sessionStorage') {
        const result = await chrome.scripting.executeScript({
          target: { tabId: currentTab.id },
          func: () => {
            const data = {};
            for (let i = 0; i < sessionStorage.length; i++) {
              const key = sessionStorage.key(i);
              data[key] = sessionStorage.getItem(key);
            }
            return data;
          }
        });
        data = result[0].result;
      }
      else if (currentStorageType === 'cookies') {
        const cookies = await chrome.cookies.getAll({ url: currentTab.url });
        data = cookies.reduce((acc, cookie) => {
          acc[cookie.name] = cookie.value;
          return acc;
        }, {});
      }

      jsonOutput.value = JSON.stringify(data, null, 2);
      showNotification(`${currentStorageType}读取成功`);
    } catch (error) {
      console.error('读取数据失败:', error);
      jsonOutput.value = '读取失败: ' + error.message;
    } finally {
      loader.style.display = 'none';
    }
  });

  // 复制到内存按钮
  copyToMemoryBtn.addEventListener('click', async () => {
    if (!isAllowOperate(currentTab)) return;
    try {
      if (!jsonOutput.value) {
        showNotification('没有数据可复制');
        return;
      }

      // 验证JSON格式
      try {
        JSON.parse(jsonOutput.value);
      } catch {
        showNotification('数据格式无效');
        return;
      }

      // 保存到Chrome存储
      await chrome.storage.local.set({
        [`storage-${currentStorageType}`]: jsonOutput.value
      });

      showNotification(`${currentStorageType}已保存到内存`);
    } catch (error) {
      console.error('复制到内存失败:', error);
      showNotification('复制到内存失败');
    }
  });

  // 粘贴按钮事件
  writeBtn.addEventListener('click', async () => {
    if (!isAllowOperate(currentTab)) return;
    if (!currentTab?.id) {
      showNotification('无法访问当前页面');
      return;
    }

    if (!pasteInput.value) {
      showNotification('请输入数据');
      return;
    }

    let parsedData;
    try {
      parsedData = JSON.parse(pasteInput.value);
    } catch (error) {
      showNotification('数据格式无效');
      return;
    }

    loader.style.display = 'flex';

    try {
      // 根据不同存储类型执行写入
      if (currentStorageType === 'localStorage') {
        await chrome.scripting.executeScript({
          target: { tabId: currentTab.id },
          func: (data) => {
            for (const [key, value] of Object.entries(data)) {
              localStorage.setItem(key, value);
            }
          },
          args: [parsedData]
        });
      }
      else if (currentStorageType === 'sessionStorage') {
        await chrome.scripting.executeScript({
          target: { tabId: currentTab.id },
          func: (data) => {
            for (const [key, value] of Object.entries(data)) {
              sessionStorage.setItem(key, value);
            }
          },
          args: [parsedData]
        });
      }
      else if (currentStorageType === 'cookies') {
        for (const [name, value] of Object.entries(parsedData)) {
          await chrome.cookies.set({
            url: currentTab.url,
            name: name,
            value: value,
            domain: new URL(currentTab.url).hostname,
            path: '/',
            sameSite: 'lax',
            secure: currentTab.url.startsWith('https:')
          });
        }
      }

      showNotification(`${currentStorageType}写入成功`);

      // 重新加载页面（可选）
      // await chrome.tabs.reload(currentTab.id);

    } catch (error) {
      console.error('写入数据失败:', error);
      showNotification('写入失败: ' + error.message);
    } finally {
      loader.style.display = 'none';
    }
  });

  // 清除按钮事件
  readClearBtn.addEventListener('click', async () => {
    if (!currentTab?.id) return;
    jsonOutput.value = '';
    showNotification('内容已清除');
  });

  // 清除按钮事件
  writeClearBtn.addEventListener('click', async () => {
    if (!currentTab?.id) return;
    pasteInput.value = '';
    showNotification('内容已清除');
  });

  // 从内存粘贴按钮
  pasteFromMemoryBtn.addEventListener('click', async () => {
    if (!isAllowOperate(currentTab)) return;
    try {
      const result = await chrome.storage.local.get(`storage-${currentStorageType}`);
      const data = result[`storage-${currentStorageType}`];

      if (data) {
        pasteInput.value = data;
        showNotification(`已从内存加载${currentStorageType}`);
      } else {
        showNotification('内存中没有存储数据');
      }
    } catch (error) {
      console.error('从内存粘贴失败:', error);
      showNotification('从内存粘贴失败');
    }
  });

  // 从剪贴板粘贴按钮
  pasteFromClipboardBtn.addEventListener('click', () => {
    if (!isAllowOperate(currentTab)) return;
    // 使用 document.execCommand('paste') 作为替代方案
    const pasteArea = document.createElement('textarea');
    pasteArea.style.position = 'fixed';
    pasteArea.style.opacity = 0;
    pasteArea.style.left = '-9999px';
    pasteArea.style.top = '-9999px';
    document.body.appendChild(pasteArea);

    pasteArea.focus();

    // 尝试使用 document.execCommand('paste')
    try {
      const success = document.execCommand('paste');
      if (success) {
        pasteInput.value = pasteArea.value;
        showNotification('已从剪贴板粘贴');
      } else {
        showNotification('无法访问剪贴板');
      }
    } catch (error) {
      console.error('从剪贴板粘贴失败:', error);
      showNotification('无法访问剪贴板');
    } finally {
      document.body.removeChild(pasteArea);
    }
  });

  // 复制按钮事件
  copyBtn.addEventListener('click', () => {
    if (!isAllowOperate(currentTab)) return;
    if (!jsonOutput.value) {
      showNotification('没有数据可复制');
      return;
    }

    // 使用 document.execCommand('copy') 作为替代方案
    const copyArea = document.createElement('textarea');
    copyArea.value = jsonOutput.value;
    document.body.appendChild(copyArea);
    copyArea.select();

    try {
      const success = document.execCommand('copy');
      if (success) {
        showNotification('已复制到剪贴板');
      } else {
        showNotification('复制失败');
      }
    } catch (error) {
      console.error('复制失败:', error);
      showNotification('复制失败');
    } finally {
      document.body.removeChild(copyArea);
    }
  });

  // 显示通知函数
  function showNotification(message) {
    notification.textContent = message;
    notification.classList.add('show');
    setTimeout(() => {
      notification.classList.remove('show');
    }, 2000);
  }

  // 是否允许操作
  function isAllowOperate(currentTab) {
    if (currentTab.url.startsWith('chrome://') ||
      currentTab.url.startsWith('edge://')) {
      showNotification('系统页面不可操作');
      return false;
    }
    return true;
  }
});